package com.ruoyi.system.api.wrapper;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;

import java.util.function.Consumer;

/**
 * 微服务包装服务基础类。
 *
 * @author ruoyi
 * @date 2023-04-26
 */
public class RemoteBaseWrapperService {

    protected <T> T processResult(R<T> result, Consumer<R<T>> fallback, Consumer<R<T>> failed, Consumer<R<T>> noData) {
        if (result == null) {
            if (fallback == null) {
                throw new ServiceException("未知异常！");
            } else {
                fallback.accept(result);
                return null;
            }
        } else if (R.FAIL == result.getCode()) {
            if (failed == null) {
                throw new ServiceException(result.getMsg());
            } else {
                failed.accept(result);
                return null;
            }
        } else if (result.getData() == null) {
            if (noData == null) {
                throw new ServiceException("未查询到数据！");
            } else {
                noData.accept(result);
                return null;
            }
        } else {
            return result.getData();
        }
    }

    protected <T> T processResult(R<T> result) {
        return processResult(result, null, null, tr -> {});
    }
}
